package com.quktzhuanka.app.https;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.TextHttpResponseHandler;
import com.quktzhuanka.app.bean.Response;
import com.quktzhuanka.app.config.Stringserializer;


import cz.msebera.android.httpclient.Header;

/**
 * 开发者：田哥哥
 * 时间:2018/7/20 09:48
 * 说明：增强版返回响应体,自动解析
 */
public abstract class onOKJsonHttpResponseHandler<T> extends TextHttpResponseHandler {

    private Class<T> aClass;
    private Gson gson;
    private TypeToken<Response<T>> fromJson;

    private Response<T> response;


    public onOKJsonHttpResponseHandler(TypeToken<Response<T>> fromJson) {
        gson = new GsonBuilder()
                .registerTypeAdapter(String.class, new Stringserializer()) //自定义反序列化
                .create();
        this.fromJson = fromJson;
    }

    public onOKJsonHttpResponseHandler() {
        gson = new Gson();
    }


    @Override
    public void onSuccess(int statusCode, Header[] headers, String responseString) {
        if (fromJson == null) {
            throw new NullPointerException("你传的TypeToken<Response<T>>为空");
        }
        Log.d("<-------", "请求响应:------->" + responseString);
        response = gson.fromJson(responseString, fromJson.getType());
        onSuccess(statusCode, response);
    }

    public abstract void onSuccess(int statusCode, Response<T> datas);
}
